<!DOCTYPE HTML>
<html>
<head>
    <title>test </title>
    <meta charset="utf-8">
    <meta name="Keywords" content="关键词,关键词">
    <meta name="Description" content="描述信息不可超过xxxx字">
    <meta http-equiv="Cache-Control" content="no-cache"/>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0, maximum-scale=1.0"/>
    <link rel="stylesheet" href="${rc.contextPath}/css/mobile-common.css?v=1.0">
    <script language="javascript" src="${rc.contextPath}/js/jquery-1.11.3.js"></script>
    <script type="text/javascript" src="${rc.contextPath}/js/mobile-back.js"></script>
    <script src="https://map.qq.com/api/gljs?v=1.exp&key=${key}"></script>
    <style type="text/css">

        /* S 产品列表 */
        .pro_cont{width:100%;}
        .pro_cont .bFoot{
            position: static;
            bottom: -50px;

        }

        .pro_cont .bBody{
            height: 400px;
            border:1px solid #E7E7E7;
            overflow-y: auto;
            background: #ddd;
            font-size:16px;
            line-height: 20px;
        }
        .pro_cont .bBody span{
            display: inline-block;
            padding:15px;
            border-radius:3px;
            margin:5px  0;
            background: #9EEA41;
        }
        .pro_cont .bBody .fromDiv span{
            background: #fff;
        }
        .pro_cont .bFoot{
            margin-top: 10px;
            margin-bottom: 120px;
        }
        .pro_cont .bFoot textarea{
            width:calc(66% - 10px);
            height: 30px;
            line-height: 30px;
            overflow-y:auto;
            outline: none;
            border:1px solid #E7E7E7;
            float:left;
            vertical-align:middle;
        }
        .pro_cont .bFoot button{
            margin-left:4%;
            width:20%;
            background:#09BB07;
            border-radius: 2px;
            color:#fff;
            height: 42px;
            border:0;
            overflow-y:auto;
            outline: none;
            float:left;
            vertical-align:middle;
            text-align:center;
        }

        .fromDiv{
            line-height: 20px;

        }
        #plist dl{
            height:30px;
            line-height: 30px;
            padding:5px 0;
            font-size:16px;
            border-bottom: 1px solid #ddd;
        }
    </style>
    <script>
        document.onclick=function(event){
            $('#clist').hide();
        }

        function append(msg,type,name){
            var text = ''
            switch(msg.type){
                case 'image':
                    text = '<img src="${rc.contextPath}'+msg.url+'" style="width: 100%;">';
                    break;
                case 'file':
                    text = msg.text + '<br><a href="${rc.contextPath}'+msg.url+'"><img src="${rc.contextPath}/images/file.jpg" style="width: 100%;"></a>';
                    break;
                case 'position':
                    text = msg.text + '<br><img onclick="showMap('+msg.lat+ ',' + msg.lng +')" src="${rc.contextPath}'+msg.url+'" style="width: 100%;">';
                    break;
                case 'audio':
                    text = '<audio controls class="audio-player" src="${rc.contextPath}'+msg.url+'" style="display:block;min-width: 200px;min-height:25px;max-width: 100%;"></audio>';
                    break;
                case 'heartbreak':
                    return ;
                default:
                    text = msg.text;
                    break;
            }
            if(type == 1){
                $('.pro_cont .bBody').append("<div align=\"right\" class=\"toDiv\">\n" +
                    "                    <span style='max-width: 70%;text-align: center;'>\n" +
                    text +
                    "                    </span>\n" +
                    "                    <font>我</font>\n" +
                    "                </div>");
            }else{
                $('.pro_cont .bBody').append("<div align=\"left\" class=\"fromDiv\">\n" +
                    "                    <font>"+name+"</font>\n" +
                    "                    <span style='max-width: 70%;text-align: center;'>\n" +
                    text +
                    "                    </span>\n" +
                    "                </div>");
            }
        }

        function sendMsg(msg){
            if(!top.websocket){
                return false;
            }
            msg.to = $('#toUser').val();
            if(!msg.to || msg.to.trim() == ''){
                alert('请选择要发送的人');
                return;
            }
            msg.from = '${userName!""}'
            top.websocket.send(JSON.stringify(msg));
            append(msg,1);
            var ele = $('.pro_cont .bBody')[0];
            ele.scrollTop = ele.scrollHeight;
            $('#msgText').val('');
        }

        $(function(){
            $("li").each(function(){
                $(this).on('click',function(){
                    var userName = $(this).data('userName');
                })
            });
            $('textarea').each(function(){
                $(this).on('focus',function(){
                    setTimeout(function(){
                        var ele = $('body')[0];
                        ele.scrollTop = ele.scrollHeight;
                    },500);
                });
                $(this).on('blur',function(){
                });
            });
        });

        var my = '${userName!"test"}';
        function websocketCallback(json){
            if('All' === $('#toUser').val()){
                append(json,2,json.from);
            }else{
                if(json.from === $('#toUser').val() && json.to === my){
                    append(json,2,'收到')
                }
            }
            var ele = $('.pro_cont .bBody')[0];
            ele.scrollTop = ele.scrollHeight;
        }

        $(function(){
            top.websocketCallback = websocketCallback;
            $('#msgText').bind('keyup', function(event) {
                if (event.keyCode == "13") {
                    //回车执行发送
                    sendMsg({type:'normal',text:$('#msgText').val()});
                }
            });
        });

        function showContacts(){
            $.ajax({
                url:'${rc.contextPath}/test/contacts',
                type:'post',
                success:function(data){
                    var fra = document.createDocumentFragment();
                    $('#clist').show();
                    data.forEach(function(item,index){
                        if('${userName!""}' != item.userId){
                            var dl = document.createElement('dl');
                            dl.innerHTML = item.userId +'('+(item.onlineState === 0 ? '离线':'在线')+')';
                            dl.style.textAlign = 'center';
                            dl.addEventListener('click',function (){
                                $('#clist').hide();
                                $('#toUser').val(item.userId);
                            })
                            fra.append(dl);
                        }
                    })
                    $('#clist').html('')
                    $('#clist').append(fra)
                }
            })
        }
    </script>
</head>
<body style="background: #ddd;">
<!-- s 页眉 -->
<header class="header">
    <img onclick="showContacts()" src="${rc.contextPath}/images/list.png" style="margin:-10px 10px 0 10px;width:30px;height:30px;vertical-align: middle;">
    <div align="center" style="display:inline-block;color:#fefefe;font-size:20px;font-weight:700;font-family:'宋体';position:relative;">
        我是${userName!''}正在跟:<input id="toUser"  style="border:0;outline: none;background: transparent;font-size: 14px;width: 40px;color: #fff;"> 聊天
    </div>
</header>

<div id="clist" style="position: fixed;top:50px;width:50%;font-size: 16px;line-height:40px;background: #6CC4FF;color: #fff;">
</div>
<!-- e 页眉 -->
<!-- s banner图 -->

<!-- e banner图 -->

<!-- s 产品列表 -->
<section class="pro_cont">
    <div class="bBody">
    </div>
    <div class="bFoot" style="display: flex;margin-bottom: 10px;padding-bottom: 10px;align-content: space-between;">
        <div onclick="changeRadio(this)" style="vertical-align: middle;width: 19%;height: 42px;line-height: 42px;text-align: center;border-right: 1px solid #ddd;margin-right:1%;-webkit-user-select: none;  -moz-user-select: none;-ms-user-select: none;user-select: none;" onselectstart="return false;" unselectable="on">
            语音
        </div>
        <textarea id="msgText" style="padding: 5px;vertical-align: middle;"></textarea>
        <div  style="vertical-align: middle;width: 20%;position: relative;">
            <button onclick="sendMsg({type:'normal',text:$('#msgText').val()});" style="width: 100%;">发送</button>
            <div id="radioBtn" style="position: absolute;width:330%;right:100%;height:42px;line-height: 42px;text-align: center;display: none;-webkit-user-select: none;  -moz-user-select: none;-ms-user-select: none;user-select: none;" onselectstart="return false" unselectable="on" oncontextmenu="return false;">按住说话</div>
        </div>
    </div>
</section>

<section>
    <span onclick="sendImg()" style="width: 50px;height:50px;line-height: 50px;text-align: center;display: inline-block;background: #fff;margin-left: 5px;border-radius: 5px;">
        <form id="imgForm" action="${rc.contextPath}/test/uploadFile" enctype="multipart/form-data"><input name="file" multiple="multiple" type="file" id="imgInput" accept="image/png,image/jpeg,image/gif" style="display: none;"></form>
        图片
    </span>
    <span onclick="sendFile()" style="width: 50px;height:50px;line-height: 50px;text-align: center;display: inline-block;background: #fff;margin-left: 5px;border-radius: 5px;">
        <form id="fileForm" action="${rc.contextPath}/test/uploadFile" enctype="multipart/form-data"><input name="file" multiple="multiple" type="file" id="fileInput" accept="application/msword,application/pdfapplication/vnd.openxmlformats-officedocument.wordprocessingml.document" style="display: none;"></form>
        文件
    </span>
    <span onclick="showMap()" style="width: 50px;height:50px;line-height: 50px;text-align: center;display: inline-block;background: #fff;margin-left: 5px;border-radius: 5px;">
        位置
    </span>
</section>

<div id="container" style="width: 100%;height: 800px;display: none;position: fixed;top:0;">
    <a href="javascript:void(0);" onclick="hideMap()" style="position: absolute;top:0;left:0;z-index: 99999;padding: 10px;background: #ddd;color:#000;">返回</a>
    <a id="choseBtn" href="javascript:void(0);" onclick="chosePoints()" style="position: absolute;top:0;right:0;z-index: 99999;padding: 10px;background: green;color:#fff;">选择</a>

    <div id="pointer" style="width: 10px;height: 10px;background: #fff;border:10px solid green;z-index: 99999;border-radius: 50%;position: fixed;top:calc(50% - 55px);left:calc(50% - 15px);">
        <div style="width: 4px;height: 30px;background: green;z-index: 99999;border-radius: 2px;margin-top:15px;margin-left:3px;"></div>
    </div>
    <div id="map" style="width: 100%;height:800px;">
    </div>

    <div id="search" style="background: #fff;position:fixed;bottom: 0;height:300px;width:100%;border-radius: 5px 5px 0 0;z-index:99999;" align="center">
        <input placeholder="输入关键字" onfocus="resizeSearch('up')" style="height: 30px;line-height: 30px;padding:5px;width: 50%;margin:10px auto;border-radius: 15px;border:0;border-bottom:1px solid black;outline: none;display: block;" onchange="keywordsChange(this)">
        <div id="plist">
        </div>
    </div>
</div>

<div id="radioCover" style="display:none;width: 100%;height: 800px;position: fixed;background: rgba(0,0,0,0.7);top:0;left:0;text-align: center;color: #fff;font-size: 16px;line-height: 800px;">录音中。。。</div>
<!-- e 产品列表 -->

<!-- s 页面导航 -->

<!-- e 页面导航 -->
<script>
    var map;
    var markerLayer;
    var mediaRecorder;
    var recordTimer;
    var chunks = [];

    function changeRadio(obj){
        var text = obj.innerHTML.trim()
        var redioBtn = document.getElementById('radioBtn');
        if(text === '语音'){
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                let constraints = { audio: true };
                navigator.mediaDevices.getUserMedia(constraints).then(function(stream){
                    mediaRecorder = new MediaRecorder(stream);
                    console.log("授权成功！");
                }).catch(function(e){
                    alert(e);
                });
            } else {
                alert("浏览器不支持");
            }
            obj.innerHTML = '文字'
            redioBtn.style.display = 'block'
            redioBtn.addEventListener('contextmenu', function(e) {
                e.preventDefault();
            });
            redioBtn.addEventListener('touchstart', function(e) {
                e.preventDefault();
                console.log("touchstart")
                var radio = document.getElementById('radio');
                recordTimer = setTimeout(function(){
                    document.getElementById('radioCover').style.display = 'block';
                    mediaRecorder.start();
                    mediaRecorder.ondataavailable = function(e) {
                        chunks.push(e.data);
                    };
                    mediaRecorder.onstop = e => {
                        var blob = new Blob(chunks, { type: "audio/mp3" });
                        var formData = new FormData();
                        formData.append('file',new File([blob],'a.mp3',{type:'audio/mp3'}))
                        $.ajax({
                            url:'${rc.contextPath}/test/uploadFile',
                            data:formData,
                            type:'post',
                            cache: false,
                            processData: false,
                            contentType: false,
                            success:function(data){
                                sendMsg({type:'audio',url:data})
                            }
                        })
                        chunks = [];
                    };
                },1000)
            });

            redioBtn.addEventListener('touchend', function(e) {
                e.preventDefault();
                console.log("touchstart")
                clearTimeout(recordTimer);
                mediaRecorder.stop();
                document.getElementById('radioCover').style.display = 'none';
            });
        }else{
            obj.innerHTML = '语音'
            redioBtn.style.display = 'none'
        }
    }
    function resizeSearch(key){
        document.getElementById('search').style.display = 'block';
        document.getElementById('choseBtn').style.display = 'inline';
        if(key === 'up'){
            document.getElementById('search').style.height = '300px';
        }else if(key == 'down'){
            document.getElementById('search').style.height = '80px';
        }else{
            document.getElementById('search').style.display = 'none';
            document.getElementById('choseBtn').style.display = 'none';
        }
    }

    function keywordsChange(input){
        $.get('${rc.contextPath}/test/mapApi?keyword=' + encodeURIComponent('keyword=' + input.value) + '&method=GET&api=/place/v1/suggestion',function(data){
            if(!data){
               alert();
               return ;
            }
            var json=  eval('('+data+')');
            var fragment = document.createDocumentFragment();
            json.data.forEach(function(item,index){
                let dl = document.createElement("dl");
                dl.innerHTML = item.title;
                dl.setAttribute('lat',item.location.lat);
                dl.setAttribute('lng',item.location.lng);
                dl.addEventListener('click',function(){
                    map.setCenter(new TMap.LatLng(dl.getAttribute("lat"), dl.getAttribute("lng")))
                    resizeSearch('down')
                });
                fragment.append(dl);
            })
            document.getElementById("plist").innerHTML = ''
            document.getElementById("plist").append(fragment);
        })
    }

    function chosePoints(){
        var pos = map.getCenter();
        var s = pos.toString().replace(' ','');
        $.get('${rc.contextPath}/test/mapApi?keyword=' + encodeURIComponent('location=' + s) + '&method=GET&api=/geocoder/v1/',function(data){
            if(!data){
                alert();
                return ;
            }
            var json=  eval('('+data+')');
            $.post('${rc.contextPath}/test/mapSnapshot',{url:'https://apis.map.qq.com/ws/staticmap/v2/?center='+ s+'&zoom=18&size=600*300&maptype=roadmap&markers=size:large|color:0xFFCCFF|label:k|'+s},function (data){
                sendMsg({
                    type:'position',
                    url:data,
                    text:json.result.address,
                    lat:s.split(',')[0],
                    lng:s.split(',')[1]
                })
                hideMap()
            });

        })

    }

    function hideMap(e){
        document.getElementById('container').style.display ='none'
        document.getElementById('map').innerHTML = ''
    }

    function sendImg(){
        var imgInput = document.getElementById("imgInput");
        imgInput.click();
        imgInput.addEventListener("change",function(){
            if(imgInput.value === ''){
                return ;
            }
            for (var i =0 ;i<imgInput.files.length;i++ ) {
                var formData = new FormData();
                formData.append('file',imgInput.files.item(i));
                $.ajax({
                    url:'${rc.contextPath}/test/uploadFile',
                    data:formData,
                    type:'post',
                    cache: false,
                    processData: false,
                    contentType: false,
                    success:function(data){
                        sendMsg({type:'image',url:data})
                    }
                })
            }
            imgInput.value = ''
        })
    }

    function sendFile(){
        var fileInput = document.getElementById("fileInput");
        fileInput.click();
        fileInput.addEventListener("change",function(){
            if(fileInput.value === ''){
                return ;
            }
            for (var i =0 ;i<fileInput.files.length;i++ ) {
                var formData = new FormData();
                var file = fileInput.files.item(i);
                formData.append('file',file);
                $.ajax({
                    url:'${rc.contextPath}/test/uploadFile',
                    data:formData,
                    type:'post',
                    cache: false,
                    processData: false,
                    contentType: false,
                    success:function(data){
                        sendMsg({type:'file',url:data,text:file.name})
                    }
                })
            }
            fileInput.value = ''

        })
    }

    function showMap(lat,lng){
        //定义地图中心点坐标
        var center = new TMap.LatLng(39.984120, 116.307484)
        resizeSearch('down')
        if(lat){
            center = new TMap.LatLng(lat, lng)
            resizeSearch()
        }
        //定义map变量，调用 TMap.Map() 构造函数创建地图
        var cont = document.getElementById('container');
        cont.style.display = 'block';
        map = new TMap.Map(document.getElementById('map'), {
            center: center,//设置地图中心点坐标
            zoom: 17.2,   //设置地图缩放级别
            pitch: 43.5,  //设置俯仰角
            rotation: 45    //设置地图旋转角度
        });
        markerLayer = new TMap.MultiMarker({
            map: map,
            styles: {
                //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
                "myStyle": new TMap.MarkerStyle({
                    "width": 25,  // 点标记样式宽度（像素）
                    "height": 35, // 点标记样式高度（像素）
                    "coloe": '0xFFCCFF',  //颜色
                    //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
                    "anchor": { x: 16, y: 32 }
                })
            },
            //点标记数据数组
            geometries: [{
                "id": "1",   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
                "styleId": 'myStyle',  //指定样式id
                "position": new TMap.LatLng(39.954104, 116.357503),  //点标记坐标位置
                "properties": {//自定义属性
                    "title": "marker1"
                }
            }]
        })
    }
    $(function () {
        document.getElementById('map').style.height = window.screen.height + 'px';
        document.getElementById('pointer').style.top = window.screen.height/2 - 55 + 'px';
        document.getElementById("container").style.height = window.screen.height + "px";
        document.getElementById("radioCover").style.height = window.screen.height + "px";
        document.getElementById("radioCover").style.lineHeight = window.screen.height + "px";
        var host = window.location.host;
        var username = "${userName!'test' }"; // 获得当前登录人员的userName
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            //alert("浏览器支持Websocket")
            var websocket = new WebSocket('wss://'+host+'${rc.contextPath}/websocket/'+ username);
            top.websocket = websocket;
            innitWebSocket();
        } else {
            //alert('当前浏览器 Not support websocket')
        }

        function innitWebSocket(){
            //连接发生错误的回调方法
            top.websocket.onerror = function(e) {
                console.log(e);
                reconnect();
            };

            //连接成功建立的回调方法
            top.websocket.onopen = function() {
                console.log("连接成功")
            };

            //接收到消息的回调方法
            top.websocket.onmessage = function(event) {
                setMessageInnerHTML(event.data);
            };

            //连接关闭的回调方法
            top.websocket.onclose = function() {
                console.log("连接关闭");
            };

            heatBreak();
        }

        function reconnect() {
            setTimeout(function () {     //没连接上会一直重连，设置延迟避免请求过多
                var websocket = new WebSocket('wss://'+host+'${rc.contextPath}/websocket/'+ username);
                top.websocket = websocket;
                innitWebSocket();
            }, 2000);
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function() {
            closeWebSocket();
        }

        //关闭WebSocket连接
        function closeWebSocket() {
            top.websocket.close();
            reconnect();
        }

        function heatBreak() {
            setTimeout(function (){
                console.log("主动心跳上报")
                sendMsg({type:'heartbreak',text:'pong'})
            },30000)
        }

        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            var data = innerHTML || "{}";
            var json = eval('(' + data + ')');
            if(json.type === 'heartbreak'){
                console.log("接收心跳包成功");
                var msg = '{"type":"heartbreak","msg":"pong"}';
                top.websocket.send(msg)
                return ;
            }
            var callback = top.websocketCallback || {};
            if (typeof callback == 'function') {
                callback(json);
            }
        }
    });
</script>
</body>
</html>